<template>
    <view class="container">
        <view class="gradient-bg">
            <view class="wave"></view>
        </view>
        <!-- 顶部标题栏 -->
        <view class="header">
            <text class="title">确认订单</text>
        </view>
        <view class="address-box" @click="editAddress">
            <view class="address-header">
                <view class="header-left">
                    <text class="address-title">收货地址</text>
                    <!-- 时间 -->
                    <view class="info-item">
                        <text class="info-value">{{orderTime}}</text>
                    </view>
                </view>
            </view>
            <view class="address-info">
                <view class="address-content" v-if="address !== '点击添加收货地址'">
                    <text class="address">{{address}}</text>
                    <text class="contact">{{name}} {{phone}}</text>
                </view>
                <view class="address-content empty" v-else>
                    <text class="empty-text">{{address}}</text>
                </view>
                <text class="arrow"><img src="static/icon/箭头.png"></text>
            </view>
        </view>
        <view class="store-box">
            <view class="store-header">
                <text class="store-name">{{storeName}}</text>
            </view>
            <view class="product-list">
                <view class="product-item" v-for="(item, index) in selectedItems" :key="index">
                    <image :src="item.imgUrl" class="product-image" mode="aspectFill"></image>
                    <view class="product-info">
                        <view class="product-top">
                            <text class="product-name">{{item.name}}</text>
                        </view>
                        <view class="price-container">
                            <text class="product-price">¥{{item.price}} x {{item.quantity}}</text>
                            <text class="product-total-price">¥{{(item.price * item.quantity).toFixed(2) }}</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 底部结算栏 -->
        <view class="footer">
            <view class="price-detail">
                <view class="total">
                    <text class="total-label">实付金额</text>
                    <view class="total-price">
                        <text class="price-symbol">¥</text>
                        <text class="price-value">{{totalPrice.toFixed(2)}}</text>
                    </view>
                </view>
            </view>
            <button class="submit-btn" @click="submitOrder" :style="submitBtnStyle">
                提交订单
            </button>
        </view>
    </view>
</template>

<script>
	import Config from '@/Config.js'
export default {
    data() {
        return {
            address: '',
            name: '',
            phone: '',
            storeName: '',
            selectedItems: [],
            totalPrice: 0,
            remark: '',
            submitBtnStyle: {
                background: 'linear-gradient(45deg, #1b76f6, #4a90e2)'
            },
            orderTime: '',
            timer: null
        }
    },
    onShow() {
        // 获取选中的商品信息
        const selectedItems = uni.getStorageSync('selectedCartItems') || [];
        this.selectedItems = selectedItems;

        // 计算总价
        this.totalPrice = selectedItems.reduce((total, item) => {
            return total + (item.price * item.quantity);
        }, 0);

        // 获取店铺名称
        if (selectedItems.length > 0) {
            this.storeName = selectedItems[0].storeName;
        }

        // 获取用户 ID
        const userInfo = uni.getStorageSync('userInfo')
        if (!userInfo) {
            return
        }
        const userId = JSON.parse(userInfo)._id

        const savedAddress = uni.getStorageSync('userAddress')
        if (savedAddress && String(savedAddress.userId) === String(userId)) {
            this.name = savedAddress.name
            this.phone = savedAddress.phone
            this.address = savedAddress.address
        } else {
            this.loadAddressInfo();
        }

        this.updateOrderTime();
        if (!this.timer) {
            this.timer = setInterval(this.updateOrderTime, 1000);
        }
    },
    onUnload() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    },
    methods: {
        async loadAddressInfo() {
            try {
                // 获取用户 ID
                const userInfo = uni.getStorageSync('userInfo')
                if (!userInfo) {
                    throw new Error('未登录')
                }
                const userId = JSON.parse(userInfo)._id

                // 清除之前存储的地址信息
                uni.removeStorageSync('userAddress')

                // 获取用户地址列表
                const response = await uni.request({
                    url: Config.api_host+'/users',
                    method: 'GET'
                })

                if (response.statusCode === 200) {
                    const users = response.data

                    const currentUser = users.find(user => String(user.id) === String(userId))

                    if (currentUser && currentUser.addresses && currentUser.addresses.length > 0) {
                        const defaultAddress = currentUser.addresses.find(addr => addr.isDefault)

                        const addressToUse = defaultAddress || currentUser.addresses[0]

                        const addressInfo = {
                            name: addressToUse.name,
                            phone: addressToUse.phone,
                            address: `${addressToUse.city} ${addressToUse.department} ${addressToUse.houseNumber}`,
                            isDefault: addressToUse.isDefault,
                            userId: userId 
                        }
                        uni.setStorageSync('userAddress', addressInfo)

                        this.name = addressToUse.name
                        this.phone = addressToUse.phone
                        this.address = addressInfo.address
                        return
                    }
                }

                // 如果没有获取到地址，显示添加地址提示
                this.name = '请添加收货地址'
                this.phone = ''
                this.address = '点击添加收货地址'

            } catch (error) {
                console.error('获取地址失败:', error)

                this.name = '请添加收货地址'
                this.phone = ''
                this.address = '点击添加收货地址'
            }
        },
        editAddress() {
            // 如果没有地址，提示用户去添加
            if (this.address === '点击添加收货地址') {
                uni.showToast({
                    title: '请先添加收货地址',
                    icon: 'none',
                    duration: 2000
                });
            }
            uni.navigateTo({
                url: '/pages/me/address?from=order'
            });
        },
        submitOrder() {
            // 检查是否有收货地址
            if (!this.address || this.address === '点击添加收货地址' || !this.name || !this.phone) {
                uni.showToast({
                    title: '请先添加收货地址',
                    icon: 'none',
                    duration: 2000
                });
                setTimeout(() => {
                    this.editAddress();
                }, 1500);
                return;
            }

            // 显示支付确认弹框
            uni.showModal({
                title: '确认生成订单吗？',
                content: '请尽快完成支付，否则将被取消',
                cancelText: '取消订单',
                confirmText: '确认订单',
                success: (res) => {
                    if (res.confirm) {
                        this.handlePaymentConfirm();
                    }
                }
            });
        },
        handlePaymentConfirm() {
            const orderData = {
                items: this.selectedItems,
                totalPrice: this.totalPrice,
                address: this.address,
                name: this.name,
                phone: this.phone,
                storeName: this.storeName,
                remark: this.remark,
                orderTime: this.orderTime
            };

            uni.setStorageSync('tempOrderData', orderData);

            uni.navigateTo({
                url: '/pages/must/pay'
            });
        },
        updateOrderTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            this.orderTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
    }
}
</script>

<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background-color: #f8f8f8;
    padding-bottom: 180rpx;
    position: relative;
}

.gradient-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 33.33vh;
    background: linear-gradient(to bottom, #007BFF, white);
    z-index: 0;
    overflow: hidden;
}

.wave {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    background: url('data:image/svg+xml,<svg viewBox="0 0 1200 120" xmlns="http://www.w3.org/2000/svg"><path d="M0 0v46.29c47.79 22.2 103.59 32.17 158 28 70.36-5.37 136.33-33.31 206.8-37.5 73.84-4.36 147.54 16.88 218.2 35.26 69.27 18.17 138.3 24.88 209.4 13.08 36.15-6 69.85-17.84 104.45-29.34C989.49 25 1113-14.29 1200 52.47V0z" fill="%23f8f8f8" fill-opacity=".25"/></svg>') repeat-x;
    background-size: 1200px 120px;
    animation: wave 10s linear infinite;
}

@keyframes wave {
    0% { background-position-x: 0; }
    100% { background-position-x: 1200px; }
}

.icon {
    font-size: 40rpx;
    margin-right: 16rpx;
}

/* 顶部标题栏 */
.header {
    height: 120rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 36rpx;
    padding: 0 20rpx;
    position: relative;
}

.title {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.address-box {
    position: relative;
    background-color: #fff;
    padding: 40rpx;
    margin: 30rpx;
    border-radius: 24rpx;
    z-index: 1;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.address-box:active {
    background-color: #f9f9f9;
}

.address-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
}

.header-left {
    display: flex;
    align-items: center;
}

.address-title {
    font-size: 40rpx;
    color: black;
    margin-bottom: 10rpx;
}

.address-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 0;
}

.address-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    &.empty {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .empty-text {
            font-size: 28rpx;
            color: #1b76f6;
        }
    }
    .address {
        font-size: 32rpx;
        color: #333;
        margin-bottom: 12rpx;
        font-weight: 500;
    }
    .contact {
        font-size: 28rpx;
        color: #666;
    }
}

.arrow {
    color: #999;
    
    margin-left: 20rpx;
    line-height: 1;
}
.arrow img{
  height: 30px;
  width: 30px;
}
.store-box {
    position: relative;
    background-color: #fff;
    padding: 40rpx;
    margin: 30rpx;
    border-radius: 24rpx;
    z-index: 1;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.store-header {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
}

.store-name {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}

.product-list {
    margin-top: 20rpx;
}

.product-item {
    display: flex;
    padding: 30rpx 0;
    border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}

.product-item:last-child {
    border-bottom: none;
}

.product-image {
    width: 160rpx;
    height: 160rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.product-info {
    flex: 1;
    margin-left: 30rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.product-top {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}

.product-name {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    flex: 1;
    margin-right: 20rpx;
}

.product-price {
    color: #e93b3b;
    font-size: 28rpx;
    margin-top: 20rpx;
    text-align: left;
}

.product-total-price {
    color: #333;
    font-size: 28rpx;
    margin-top: -30rpx;
    text-align: right;
}

.price-container {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.price-symbol {
    font-size: 24rpx;
    color: #e74c3c;
    margin-right: 4rpx;
}

.price {
    font-size: 36rpx;
    color: #e74c3c;
    font-weight: bold;
}

.order-info {
    position: relative;
    background-color: #fff;
    padding: 40rpx;
    margin: 30rpx;
    border-radius: 24rpx;
    z-index: 1;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
}

.info-item:last-child {
    margin-bottom: 0;
}

.info-label {
    font-size: 28rpx;
    color: #666;
}

.info-value {
    margin-left: 200rpx;
    font-size: 28rpx;
    color: #333;
}

.remark-input {
    flex: 1;
    font-size: 28rpx;
    text-align: right;
    color: #333;
}

.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
    z-index: 10;
}

.price-detail {
    flex: 1;
}

.total {
    display: flex;
    align-items: baseline;
}

.total-label {
    font-size: 28rpx;
    color: #666;
    margin-right: 12rpx;
}

.total-price {
    display: flex;
    align-items: baseline;
}

.price-value {
    font-size: 40rpx;
    color: #e74c3c;
    font-weight: bold;
}

.price-desc {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
}

.submit-btn {
    width: 240rpx;
    height: 80rpx;
    color: #fff;
    font-size: 32rpx;
    border-radius: 10rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;
    margin-left: 30rpx;
    box-shadow: 0 8rpx 16rpx rgba(27, 118, 246, 0.3);
    transition: all 0.3s ease;
	background-color: #007BFF;
}

.submit-btn:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 8rpx rgba(27, 118, 246, 0.3);
}
</style>    